<template>
	<view class="diary">
		<Loading :loadModal="loadModal" :hint="hint"></Loading>
		<block v-if="DiaryTab.length>0">
			<view class="cu-timeline" v-for="item in DiaryTab" :key="item._id">
				<view class="cu-time" v-if="item.son.length>0">{{item._id}}</view>
				<view class="cu-item" v-for="(it,idx) in item.son" :key="idx">
					<view class="content">
						<view class="cu-bar cu-capsule radius diary_time">
							<view>
								<view class="cu-tag" :class="it.type=='上午'?'bg-cyan':'bg-red'">{{it.type}}</view>
								<view class="cu-tag line-cyan">{{it.time}}</view>
							</view>
							<view class="action">
								<text class='cu-tag cuIcon-post lg text-blue' @click="openDiary(1,it)"></text>
								<text class='cu-tag cuIcon-backdelete lg text-red' @click="delDiary(it._id)"></text>
							</view>
						</view>
						<rich-text class="html" :nodes="it.diary_body|formatRichText"></rich-text>
					</view>
				</view>
			</view>
		</block>
		
		<Nodata :noModal="nodata"></Nodata>
		<!-- 添加按钮 -->
		<movable-area>
			<movable-view :x="x" :y="y" direction="all" class="addButton" v-if="!window" @click="openDiary">
				<image :src="imgUrl+'static/add.png'" />
			</movable-view>
		</movable-area>
		<!-- 弹出窗口 -->
		<view v-if="window" class="windowBg" @touchmove.stop.prevent = "doNothing" @tap="closeDiary"></view>
		<view v-if="window" class="addWindow" :animation="ani">
		    <input :disabled="curSts == 1" class="taskInput" :value="diary_title" placeholder="日记标题..."
		        @input='getDiaryInput' />
		    <view class='wrapper'>
		        <view class='toolbar' @tap="format">
		           <view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
		            <view :class="formats.italic ? 'ql-active' : ''" class="iconfont icon-zitixieti" data-name="italic"></view>
		            <view :class="formats.strike ? 'ql-active' : ''" class="iconfont icon-zitishanchuxian" data-name="strike"></view>
								<view class="iconfont icon-outdent" data-name="indent" data-value="-1"></view>
								<view class="iconfont icon-indent" data-name="indent" data-value="+1"></view>
		            <view class="iconfont icon-fengexian" @tap="insertDivider"></view>
								<view class="iconfont icon-charutupian" @tap="insertImage"></view>
		        </view>
		        <editor id="editor" class="ql-container"  placeholder="日记描述..." showImgSize showImgToolbar showImgResize @statuschange="onStatusChange" :read-only="curSts == 1"  @ready="onEditorReady">
		        </editor>
		    </view>
		    <view class="cu-bar taskSubmit">
						<button v-if="!isEditor" class="lines-blue" @tap="addDiary">提交</button>
						<button v-else class="line-green" @tap="updateDiary">更新</button>
						<button class="line-orange" @tap="closeDiary">取消</button>
		    </view>
		</view>
	</view>
</template>

<script>
	import Loading from '../../components/loading.vue';
	import Nodata from '../../components/nodata.vue';
	import util from '../../utils/util.js';
	import api from '../../utils/api.js';
	export default {
		components: {
			Loading,
			Nodata
		},
		data() {
			return {
				imgUrl: getApp().globalData.imgUrl,
				admin_id:getApp().globalData.admin_id,
				loadModal: false, //加载
				hint: '加载中...',
				nodata: false,
				userInfo:{},
				// pageInex:1,//第一页
				DiaryTab: [],
				
				x: wx.getSystemInfoSync().windowWidth - 10,
				y: wx.getSystemInfoSync().windowHeight - 100 - 10,
				window:false,
				ani:{},
				formats: {},
				// 任务数据
				diary_id: '',
				diary_title: '',
				diary_body: '',
				// 是否是编辑
				isEditor: false,
				// 当前任务状态，用来判断是否可以更新
				curSts: 0,
			}
		},
		props: ['pageInex'],
		created: function() {
			this.getDiaryTab();
		},
		onLoad() {
			uni.loadFontFace({
				family: 'Pacifico',
				source: 'url("https://sungd.github.io/Pacifico.ttf")'
			});
			let userInfo =getApp().globalData.userInfo;
			if (Object.keys(userInfo).length>0) {
			  this.userInfo = userInfo;		
			}
		},
		methods: {
			doNothing:function(){}, 
			getDiaryTab:async function(refresh = '') {
				this.DiaryTab = [];
				let res=await api.getDiaryTab();
				if(res.errMsg=="cloud.callFunction:ok"){
					this.DiaryTab = res.result.list;
					if(this.DiaryTab.length==0){
						this.nodata=true;
					}
					for(let i=0;i<this.DiaryTab.length;i++){
						this.DiaryTab[i].son=[];
					}
					this.getDiary(refresh);
				}
			},
			getDiary:async function(refresh = '', pageInex = 1) {
				this.hint = refresh == 'below' ? '刷新中...' : '加载中...';
				this.loadModal = true;
				let res=await api.getDiary(pageInex);
				this.loadModal = false;
				uni.stopPullDownRefresh();
				if(res.errMsg=="cloud.callFunction:ok"){
					let list = res.result.list;
					if (list.length == 0) {
						uni.showToast({
							title: '没有更多数据了！',
							icon: 'none',
							duration: 2000
						})
						return false;
					}
					let time = new Date().getTime();
					let atYear = util(time).split('-')[0];
					this.DiaryTab.forEach(item => {
						list.forEach(it => {
							it.time = util(parseInt(it.diary_time), 4);
							it.type = util(parseInt(it.diary_time), 4).split(':')[0] > 12 ?'下午' : '上午';
							if (it.diary_data == item._id) {
								item.son.push(it);
							}
						})
						item._id = item._id.split('-')[0] == atYear ? item._id.substring(5, 10) :item._id;
					})
				}		
			},
			/**
				 * 打开日志添加窗口
			*/
			openDiary(type=0,info={}){
				if(type==1){
					this.isEditor=true;
					this.diary_id=info._id;
					this.diary_title=info.diary_title;
					this.diary_body=info.diary_body;
				}
				
				this.window=true;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
					delay: 100
				});
				animation.opacity(1).translateY(-375).step();
				this.ani=animation.export();
			},
			/**
			 * 新增任务
			 */
			addDiary:async function() {
				if (this.diary_title == '') {
					return uni.showToast({
						title: '请输入任务标题',
						icon: 'none',
						duration: 1500
					})
				}
				const that = this;
				that.editorCtx.getContents({
					success: function (res) { 
						let data={
							diary_admin_id: that.admin_id,
							diary_title: that.diary_title,
							diary_body: res.html
						}
						new Promise(resolve => {
								resolve(api.updateDiary('',data));
						}).then(result => {
							if(result.result){
								that.closeDiary()
								that.getDiaryTab()
								uni.showToast({
									title: '提交成功.',
									icon: 'none',
									duration: 1500
								})
							}else{
								uni.showToast({
									title: '提交异常！',
									icon: 'none',
									duration: 1500
								})
							}
						})
					},
					fail: function (error){
						console.log(error)
					}
				})
			},
			/**
			 * 更新任务
			 */
			updateDiary:async function() {
				if (this.curSts == 1) {
					return uni.showToast({
						title: '已完成任务不支持更新',
						icon: 'none',
						duration: 1500
					})
				}
				if (this.diary_id == '') {
					return uni.showToast({
						title: '系统异常',
						icon: 'none',
						duration: 1500
					})
				}
				if (this.diary_title == '') {
					return uni.showToast({
						title: '请输入任务标题',
						icon: 'none',
						duration: 1500
					})
				}
				const that = this;
				that.editorCtx.getContents({
					success: function (res) {   
						let data={
							diary_admin_id: that.admin_id,
							diary_title: that.diary_title,
							diary_body: res.html
						}
						new Promise(resolve => {
								resolve(api.updateDiary(that.diary_id,data));
						}).then(result => {
							if(result.result){
								that.closeDiary()
								that.getDiaryTab()
								uni.showToast({
									title: '更新成功.',
									icon: 'none',
									duration: 1500
								})
							}else{
								uni.showToast({
									title: '更新异常！',
									icon: 'none',
									duration: 1500
								})
							}
						})
					},
					fail: function (error){
						console.log(error)
					}
				})
			},
			//删除任务
			delDiary:async function(id){
				let that=this;
				if(!id){
					return uni.showToast({
						title: '系统异常',
						icon: 'none',
						duration: 1500
					})
				}
				wx.showModal({
					title: '提示',
					content: '是否确认删除日记',
					success: function(res) {
						if (res.confirm) {
							new Promise(resolve => {
									resolve(api.delDiary(id));
							}).then(result => {
								if(result.result){
									that.getDiaryTab()
									uni.showToast({
										title: '删除成功.',
										icon: 'none',
										duration: 1500
									})
								}else{
									uni.showToast({
										title: '删除异常！',
										icon: 'none',
										duration: 1500
									})
								}
							})
	
						} else if (res.cancel) {
							// console.log('用户点击取消')
						}
					}
				})
			},
			/**
			 * 关闭任务添加窗口
			 */
			closeDiary() {
				this.window=false;
				var animation = uni.createAnimation({
					duration: 1000,
					timingFunction: 'ease',
					delay: 100
				});
				animation.opacity(1).translateY(315).step()
				this.ani=animation.export();
				// 清空数据
				this.diary_id = '';
				this.diary_title= '';
				this.diary_body= '';
				this.isEditor=false;
				this.onEditorReady()
			},
			/**
			 * 编辑器数据回显
			 */
			format: function(e) {
				let {name,value} = e.target.dataset
				if (!name) {return false}
				this.editorCtx.format(name, value)
			},
			onStatusChange: function(e) {
				this.formats =e.detail
			},
			insertDivider: function() { //插入分隔符
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success')
					}
				})
			},
			insertImage: async function() { //插入图片
				let that = this;
				uni.chooseImage({
					count: 6,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						const tasks = [];
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							const promise = that.getTempUrl(res.tempFilePaths[i]);
							tasks.push(promise);
						}
						Promise.all(tasks).then((result) => {
							console.info(result);
							for (let i = 0; i < result.length; i++) {
								that.editorCtx.insertImage({
									src: result[i],
									alt: '图像',
									success: function() {
										console.log('insert image success')
									}
								})
							}
						}).catch((error) => {
							console.log(error)
						})
					}
				})
			},
			getTempUrl: async function(filePath) { //插入图片
				let src = '';
				let suffix = /\.[^\.]+$/.exec(filePath)[0];
				const cloudPath = 'images/diary/' + new Date().getTime() + suffix;
				let imgRes = await api.uploadFile(cloudPath, filePath);
				if (imgRes.errMsg == 'cloud.uploadFile:ok') {
					let file = await api.getTempUrl(imgRes.fileID);
					if (file.errMsg == 'cloud.getTempFileURL:ok') {
						src = file.fileList[0].tempFileURL;
					}
				};
				return src;
			},
			onEditorReady: function() {
				let _this=this;
				uni.createSelectorQuery().in(this).select('#editor').context((res) => {
					res.context.setContents({
						html: _this.diary_body
					})
					this.editorCtx = res.context
				}).exec()
			},
			/**
			 * 获取input输入的数据
			 */
			getDiaryInput(e) {
				this.diary_title=e.detail.value;
			},
		},
		filters: {
			/**
			 * 处理富文本里的图片宽度自适应
			 * 1.去掉img标签里的style、width、height属性
			 * 2.img标签添加style属性：max-width:100%;height:auto
			 * 3.修改所有style里的width属性为max-width:100%
			 * 4.去掉<br/>标签
			 * @param html
			 * @returns {void|string|*}
			 */
			formatRichText (html) { //控制小程序中图片大小
					let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
							match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
							match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
							match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
							return match;
					});
					newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
							match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
							return match;
					});
					newContent = newContent.replace(/<br[^>]*\/>/gi, '');
					newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
					return newContent;
			}	
		}
}
</script>

<style>
@import "../../static/jyf-parser/iconfont.css";

.diary {
margin-bottom: 67.5px;
}

.cu-timeline .cu-time {
width: 160rpx;
}
/* 添加按钮 */
.addButton image {
/*  position: fixed;
	bottom: 140px; */
	right: 40px;
	width: 100rpx;
	    height: 100rpx;
	}
	movable-area {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		pointer-events: none; //设置area元素不可点击，则事件便会下移至页面下层元素
		z-index: 9;
	}
	movable-view {
		pointer-events: auto; //可以点击
		width: 100rpx;
		height: 100rpx;
	}
	
	/* 添加窗口 */
	.windowBg{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0,0,0,0.3);
	}
	.addWindow {
	    background-color: #f8f8f8;
	    position: fixed;
	    /* height: 420px; */
	    height: (650/2)rpx;
	    width: 100%;
	    bottom: -375px;
	    padding-top: 10rpx;
			/* border: 1px blue solid; */
			margin-bottom: 100rpx;
			opacity: 1;
			transform: translateY(-375);
	}
	
	.taskInput {
	    background-color: white;
	    height: 70rpx;
	    margin: 15rpx 15rpx 15rpx 15rpx;
	    padding-left: 15rpx;
	}
	
	.wrapper {
	    padding: 15rpx;
	    padding-top: 10rpx;
	}
	
	.toolbar {
			z-index: 99;
	    box-sizing: border-box;
	    background: #fff;
	    font-family: 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
	}
	
	.iconfont {
	    display: inline-block;
	    padding: 8px 8px;
	    width: 40px;
	    height: 40px;
	    cursor: pointer;
	    font-size: 20px;
	}
	
	.ql-container {
	    box-sizing: border-box;
	    padding: 10px 10px;
	    width: 100%;
	    min-height: 350rpx;
	    border-top: 1px solid #ccc;
	    background: #fff;
	    font-size: 16px;
	    line-height: 1.5;
	}
	
	/* 任务提交按钮 */
	.taskSubmit {
	    margin-top: 10rpx;
	    padding-bottom: 20rpx;
	}
	.taskSubmit  button{
		width: 40%;
		height: 90rpx;
		line-height: 90rpx;
	}
	.diary_time{
		min-height: 50rpx;
		margin-bottom: 10px;	
	}
	.html image{
		max-width: 100% !important;
	}

</style>
